// 用axios实例，方便维护代码,不会污染axios
import axios from 'axios'
// 因为这里的this并不指向vue实例，所以要用导入toast的方式
import { Toast } from 'vant'

const instance = axios.create({
  baseURL: 'http://smart-shop.itheima.net/index.php?s=/api',
  timeout: 1000,
  headers: { platform: 'H5' }
})

instance.interceptors.request.use(function (config) {
  // Do something before request is sent
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })

  // 只有当userinfo存在时，才要求携带token
  if (localStorage.getItem('userinfo')) {
    const { token } = JSON.parse(localStorage.getItem('userinfo'))
    config.headers['Access-Token'] = token
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
}

)

// Add a response interceptor
instance.interceptors.response.use(function onFulfilled (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  const result = response.data
  Toast.clear()
  //   如果只对验证码进行格式校验，当验证码内容错误时，则还是会登录，所以可以在把数据返回之前进行拦截处理
  if (result.status !== 200) {
    if (!result.message) {
      Toast('服务器繁忙')
    }
    Toast(result.message)
    return Promise.reject(result.message)
  } else {
    return result
  }
}, function onRejected (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error)
})

export default instance
